package com.derbysoft.lowcostadapter.commons.redis.service.impl;

import com.derbysoft.lowcostadapter.commons.model.Hotel;
import com.derbysoft.lowcostadapter.commons.model.Status;
import com.derbysoft.lowcostadapter.commons.redis.service.HotelCacheService;
import com.derbysoft.lowcostadapter.commons.redis.utils.KeyValueHelper;
import com.derbysoft.redis.clients.normal.SingleJedis;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.PipelineBlock;

import java.util.ArrayList;
import java.util.List;

@Component("hotelCacheService")
public class HotelCacheServiceImpl implements HotelCacheService {

    private static Log logger = LogFactory.getLog(HotelCacheServiceImpl.class);

    @Autowired
    private SingleJedis systemConfigRedis;

    @Override
    public Hotel loadByPassport(String passport) {
        return loadByKey(Hotel.PASSPORT_PREFIX + passport);
    }

    @Override
    public Hotel loadById(String propertyId) {
        return loadByKey(Hotel.ID_PREFIX + propertyId);
    }

    @Override
    public void saveAll(List<Hotel> hotels) {
        final List<SetEntity> setEntities = new ArrayList<SetEntity>();
        for (Hotel hotel : hotels) {
            setEntities.add(SetEntity.build(Hotel.ID_PREFIX + hotel.getPropertyID(), hotel.value()));
            setEntities.add(SetEntity.build(Hotel.PASSPORT_PREFIX + hotel.getPassport(), hotel.value()));
        }
        try {
            systemConfigRedis.pipelined(new PipelineBlock() {
                @Override
                public void execute() {
                    for (SetEntity setEntity : setEntities) {
                        set(setEntity.getKey(), setEntity.getValue());
                    }
                }
            });
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }


    private Hotel loadByKey(String key) {
        String value = systemConfigRedis.get(key);
        if (value == null) {
            return null;
        }
        Hotel hotel = new Hotel();
        hotel.setPropertyID(Integer.parseInt(value.split(KeyValueHelper.SEPARATOR)[0]));
        hotel.setPassport(value.split(KeyValueHelper.SEPARATOR)[1]);
        hotel.setName(value.split(KeyValueHelper.SEPARATOR)[2]);
        hotel.setStatus(value.split(KeyValueHelper.SEPARATOR)[3].toUpperCase().equals("ENABLED")
                ? Status.ENABLED
                : Status.DISABLED);
        return hotel;
    }
}
